<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="http://novel-pay.oss-cn-shenzhen.aliyuncs.com/css/common.css">
    <script type="text/javascript">
        // 使用rem 动态修改html 的font-size大小
        !(function (doc, win) {
            var docEle = doc.documentElement,
                evt = "onorientationchange" in window ? "orientationchange" : "resize",
                fn = function () {
                    var docW = docEle.clientWidth;
                    var width = docW > 750 ? 750 : docW;
                    width && (docEle.style.fontSize = Math.floor(100 * (width / 750) / 2) * 2 + "px");
                };
            win.addEventListener(evt, fn, false);
            doc.addEventListener("DOMContentLoaded", fn, false);

        }(document, window));
    </script>
    <style>
        .title{
            line-height: 1rem;
        }
        
        .fixed-footer{
            padding:.2rem .3rem;
            background-color: #FFF;
        }
        .recharge-btn{
            position: fixed;
            bottom:0;
            left:0;
            width:100%;
            color:#FFF;
            font-size: .36rem;
            text-align: center;
            line-height: .98rem;
            background-color: #20D1AC;
        }
    </style>
    <title>充值支付</title>
</head>
<!-- 本页面所有js均向下兼容(fuck ios8) 在线编译 https://babeljs.io/repl-->
<body>
    <div id="app">
        <recharge-dialog></recharge-dialog>
    </div>
    </script>
    <!-- 第一步快速执行自动拉取支付 -->
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script src="https://cdn.bootcss.com/axios/0.17.1/axios.min.js"></script>
    <script>
        var apiPreUrl = "http://pay.yyxiaoshuo.com.cn";
        var WXapp = {
            config: {
                /* gid:"",
                appId: "",
                timestamp: "",
                nonceStr: "",
                paySign: "",
                signType: "",
                package: "",
                orderNo: "", */
                token: "<?=$token?>",
                successUrl: "<?=$success_url?>",
                failUrl: "<?=$fail_url?>?",
                merchantHost: "<?=$merchant_host?>",
                bookId:"<?=$book_id?>",
                coins:"<?=$coins?>"
            },
            rechargeList:'<?=$recharge_list?>',
            wxPay: function (config) {
                var app = this;
                wx.config({
                    // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    debug: false,
                    appId: config.appId, // 必填，公众号的唯一标识
                    timestamp: config.timestamp, // 必填，生成签名的时间戳
                    nonceStr: config.nonceStr, // 必填，生成签名的随机串
                    signature: config.paySign, // 必填，签名，
                    jsApiList: ["chooseWXPay"] // 必填，需要使用的JS接口列表，所有JS接口列表
                });

                wx.ready(function () {
                    wx.chooseWXPay({
                        timestamp: config.timestamp,
                        nonceStr: config.nonceStr,
                        package: config.package,
                        signType: config.signType,
                        paySign: config.paySign,
                        success: function (res) {
                            app.paySuccess();
                            resolve(res);
                        },
                        cancel: function (res) {
                            // 支付取消的回调函数
                            app.payCancel();
                            reject(res);
                        },
                        error: function (res) {
                            // 支付失败的回调函数
                            app.payError();
                        }
                    });
                });
            },
            paySuccess:function() {
                var app = this;
                window.location.href = app.config.successUrl;
            },
            payCancel:function() {
                var app = this;
                alert("支付已取消");
                axios({
                    method: 'POST',
                    url: apiPreUrl+'/recharge/cancel',
                    data: {
                        token: app.config.token,
                        order_no: app.config.orderNo
                    },
                }).then(function (response) {
                    //window.location.href = app.config.failUrl;
                });
            },
            payError:function() {
                var app = this;
                alert("支付失败");
                axios({
                    method: 'POST',
                    url: apiPreUrl+'/recharge/error',
                    data: {
                        token: app.config.token,
                        order_no: app.config.orderNo
                    },
                }).then(function (response) {
                    //window.location.href = app.config.failUrl;
                });
            },
            init: function () {
                //this.wxPay(this.config);
            }
        };
    </script>
    <script>
        function objExtend(){
            /*对象扩展*/
            var options, name, src, copy, copyIsArray, clone,
                target = arguments[ 0 ] || {},
                i = 1,
                length = arguments.length,
                deep = false;
            if ( typeof target === "boolean" ) {
                deep = target;
                target = arguments[ i ] || {};
                i++;
            }
            if ( typeof target !== "object" && typeof target !== "function" ) {
                target = {};
            }
            if ( i === length ) {
                target = this;
                i--;
            }
            for ( ; i < length; i++ ) {
                if ( ( options = arguments[ i ] ) != null ) {
                    for ( name in options ) {
                        src = target[ name ];
                        copy = options[ name ];
                        if ( target === copy ) {
                            continue;
                        }
                        if ( deep && copy && (copyIsArray = Array.isArray( copy )) ) {
                            if ( copyIsArray ) {
                                copyIsArray = false;
                                clone = src && Array.isArray( src ) ? src : [];

                            } else {
                                clone = src ? src : {};
                            }
                            target[ name ] = this.extend( deep, clone, copy );
                        } else if ( copy !== undefined ) {
                            target[ name ] = copy;
                        }
                    }
                }
            }
            // Return the modified object
            return target;
        }
    </script>
    <!-- 第二步开始利用vue渲染页面并绑定对应的充值事件 -->
    <script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
    <script>
        "use strict";
        
        Vue.component('rechargeDialog', {
            template: "<div class=\"page-wrap h100 bgFFF\">\n                <div class=\"title\">\u5F53\u524D\u4F59\u989D</div>\n\t            <div class=\"balance\">" + WXapp.config.coins + "\u4E66\u5E01</div>\n                <div class=\"title gray\">\u9009\u62E9\u5145\u503C\u91D1\u989D(1\u5143=100\u4E66\u5E01)</div>\n                <recharge-list\n                    :rechargeId.sync=\"rechargeId\"\n                    :defaultGid=\"" + WXapp.config.gid + "\">\n                </recharge-list>\n                <div class=\"recharge-btn\" @click=\"chooseRecharge\">\u786E\u8BA4\u5145\u503C</div>\n            </div>",
            mixins: [{
                mounted: function mounted() {},
                computed: {
                    token: function token() {
                        return WXapp.config.token;
                    }
                },
                methods: {
                    chooseRecharge: function chooseRecharge() {
                        var success_url = encodeURIComponent(location.origin + '/#/mine');
                        var fail_url = encodeURIComponent(location.origin + '/#/mine/recharge');
                        this.createOrder(this.rechargeId);
                    },
                    rechargeNow: function rechargeNow(rechargeId, success_url, fail_url, book_id) {
                        var host = location.host;
                        var url = apiPreUrl + '/recharge/pay?token=' + undefined.token + '&gid=' + rechargeId + '&success_url=' + success_url + '&fail_url=' + fail_url + '&merchant_host=' + host;
        
                        if (typeof book_id !== 'undefined') {
                            url += '&book_id=' + book_id;
                        }
                        setTimeout(function () {
                            window.location.href = url;
                        });
                    },
                    paySuccess: function paySuccess() {
                        var _this = this;
        
                        this.$common.toast({
                            "text": "充值成功",
                            "type": "success"
                        }).then(function () {
                            _this.$router.push({
                                name: "mine"
                            });
                        });
                    },
                    payError: function payError() {
                        this.$common.toast({
                            "text": "充值失败",
                            "type": "cancel"
                        });
                    }
                }
            }],
            data: function data() {
                return {
                    rechargeId: null
                };
            },
            methods: {
                onRecharge: function onRecharge(id) {
                    this.createOrder(id);
                },
                createOrder: function createOrder(id) {
                    axios({
                        method: 'POST',
                        url: apiPreUrl + '/recharge/create-order',
                        data: {
                            token: WXapp.config.token,
                            gid: id,
                            merchant_host: WXapp.config.merchantHost,
                            book_id: WXapp.config.bookId || ''
                        }
                    }).then(function (response) {
                        var resConfig = response.data.data;
                        WXapp.config = objExtend(WXapp.config, resConfig);
                        WXapp.wxPay(WXapp.config);
                    }, function () {
                        alert("生成订单失败,请重试");
                    });
                }
            }
        });
    </script>
    <script>
        "use strict";
        
        Vue.component('rechargeList', {
            template: "<transition-group name=\"fade\" class=\"df recharge-list\" tag=\"div\">\n                            <div class=\"recharge-item df df-absolute-center\" \n                                v-for=\"item in rechargeInfo\" \n                                :key=\"item.gid\" \n                                @click=\"onChange(item.gid)\" \n                                :class=\"{'active':selfRechargeId == item.gid}\">\n                                <div>\n                                    <div class=\"recharge-amount\" v-text=\"item.price+'\u5143'\"></div>\n                                    <div class=\"foz22 gray\" v-text=\"item.tips\"></div>\n                                </div>\n                                \n                                <!-- <div class=\"theme-color present\" v-text=\"item.tips2\"></div> -->\n                            </div>\n                        </transition-group>",
            props: {
                rechargeId: null,
                defaultGid: null,
                isUseDefault: {
                    type: Boolean,
                    default: true
                }
            },
            data: function data() {
                return {
                    selfRechargeId: this.rechargeId,
                    rechargeInfo: []
                };
            },
            created: function created() {
                this.pageInit();
            },
            mounted: function mounted() {
                
            },
        
            watch: {
                selfRechargeId: function selfRechargeId(curVal, oldVal) {
                    this.$emit("update:rechargeId", curVal);
                }
            },
            compouted: {},
            methods: {
                pageInit: function pageInit() {
                    this.getRechargeInfo();
                },
                getRechargeInfo: function getRechargeInfo() {
                    /* this.$api.getRechargeInfo().then( res => {
                        this.rechargeInfo = res;
                        this.selfRechargeId = res[1].gid;
                    }); */
                    this.rechargeInfo = JSON.parse(WXapp.rechargeList);
                    if (!!this.isUseDefault) {
                        this.selfRechargeId = this.defaultGid || this.rechargeInfo[1].gid;
                    }
                },
                onChange: function onChange(id) {
                    this.selfRechargeId = id;
                    this.$emit("onRecharge", id);
                }
            }
        }); 
    </script>
    <script>
        // 在所有资源加载完毕执行初始化
        window.onload = function () {
            WXapp.init();
            new Vue({
                el: '#app',
            })
        }
    </script>
</body>
</html>